package table

import (
	"gorm.io/gorm"
	"i18n-template/components"
)

type Article struct {
	gorm.Model
	Title       string `json:"title" gorm:"type:string;size:256;comment:文章标题"`
	Cover       string `json:"cover" gorm:"type:string;size:512;comment:文章封面"`
	Author      string `json:"author" gorm:"type:string;size:128;comment:文章作者"`
	Keywords    string `json:"keywords" gorm:"type:string;size:512;comment:文章关键字"`
	Description string `json:"description" gorm:"type:string;size:512;comment:文章描述"`
	Content     string `json:"content" gorm:"comment:文章内容"`
	Language    string `json:"language" gorm:"type:string;size:10;comment:文章的语言"`
}

func (a Article) TableName() string {
	return "article"
}

func (a Article) GenerateArticle(ar *Article) error {
	return components.DB.Model(&Article{}).Save(ar).Error
}

func (a Article) FindArticleByID(id string) (*Article, error) {
	article := &Article{}
	err := components.DB.Model(&Article{}).Where("id = ?", id).First(article).Error
	return article, err
}

func (a Article) FindAllArticle(lan, title string) []*Article {
	articles := make([]*Article, 20)
	d := components.DB.Model(&Article{}).Where("language = ?", lan)
	if title != "" {
		d = d.Where("title LIKE ?", "%"+title+"%")
	}
	d.Find(&articles)
	return articles
}

func (a Article) PatchArticleByID(ar *Article) error {
	return components.DB.Model(&Article{}).Where("id = ?", ar.ID).Updates(Article{
		Title:       ar.Title,
		Cover:       ar.Cover,
		Author:      ar.Author,
		Keywords:    ar.Keywords,
		Description: ar.Description,
		Content:     ar.Content,
		Language:    ar.Language,
	}).Error
}

func (a Article) DeleteArticleByID(id uint) error {
	return components.DB.Model(&Article{}).Where("id = ?", id).First(&Article{}).Delete(&Article{}).Error
}
